import os
from src.modules.file_manager import FileManager
from src.utils.logger import log_info, log_error

from .video_normalizer import VideoNormalizer
from .audio_processor import AudioProcessor
from .subtitle_burner import SubtitleBurner
from .transition_merger import TransitionMerger
from .utils import run_ffmpeg

class VideoMerger:
    """专门处理视频合并、转换和添加过渡效果的类"""
    
    def __init__(self, transition_effect, transition_duration, startupinfo=None, logger=None):
        """
        初始化VideoMerger
        
        :param startupinfo: 用于subprocess的startupinfo对象，默认为None
        :param transition_effect: 默认的过渡效果类型
        :param transition_duration: 默认的过渡效果持续时间（秒）
        """
        self.startupinfo = startupinfo
        self.file_manager = FileManager(logger=logger)
        self.transition_effect = transition_effect
        self.transition_duration = transition_duration
        self.logger = logger
        
        # 初始化子模块
        self.video_normalizer = VideoNormalizer(startupinfo, logger)
        self.audio_processor = AudioProcessor(startupinfo, logger)
        self.subtitle_burner = SubtitleBurner(startupinfo, logger)
        self.transition_merger = TransitionMerger(startupinfo, transition_effect, transition_duration, logger)
    
    def _log_error(self, message):
        self.logger(message, level="error") if self.logger else log_error(message)
    
    def cleanup(self):
        """清理所有临时文件和目录"""
        self.file_manager.cleanup_category(f"video_merger")
    
    def _validate_video_paths(self, *video_paths):
        """验证视频文件路径是否存在"""
        if not video_paths:
            raise ValueError("至少需要一个视频文件路径")
        
        for path in video_paths:
            if not os.path.exists(path):
                raise FileNotFoundError(f"视频文件不存在: {path}")
        
        return True
    
    def separate_audio_from_video(self, video_path, output_path=None):
        """使用 demucs 分离视频中的人声，创建一个没有人声的视频版本。"""
        return self.audio_processor.separate_audio_from_video(video_path, output_path)
    
    def merge_videos_with_transitions(self, *video_paths, output_path=None, remove_voice=False):
        """使用filter_complex一步完成多视频合并和过渡效果"""
        return self.transition_merger.merge_videos_with_transitions(
            *video_paths, 
            output_path=output_path, 
            remove_voice=remove_voice,
            validate_func=self._validate_video_paths,
            separate_audio_func=self.separate_audio_from_video
        )
    
    def merge_video_with_audio(self, video_path, output_path, audio_path, 
                              subtitle_path=None, burn_subtitles=True, 
                              audio_volume=1.0, original_volume=0.8):
        """合并视频、音频和字幕文件，智能调整音量以确保人声清晰可闻"""
        return self.audio_processor.merge_video_with_audio(
            video_path, output_path, audio_path,
            subtitle_path=subtitle_path, 
            burn_subtitles=burn_subtitles,
            audio_volume=audio_volume, 
            original_volume=original_volume
        )
    
    def apply_fade_effects(self, video_path, temp_dir, fade_duration=1.0):
        """为视频添加淡入淡出效果"""
        from src.modules.fade_processor import FadeProcessor
        fade_processor = FadeProcessor(startupinfo=self.startupinfo, logger=self.logger)
        return fade_processor.apply_video_fade_out(
            video_path=video_path,
            output_path=os.path.join(temp_dir, f"fade_out_{os.path.basename(video_path)}"),
            fade_duration=fade_duration
        )
    
    def burn_subtitles_to_video(self, video_path, subtitle_path, output_path=None,
                              font_size=10, margin_v=25, font_color="white", font_name=None):
        """将字幕烧录到视频中"""
        return self.subtitle_burner.burn_subtitles_to_video(
            video_path, subtitle_path, output_path,
            font_size=font_size, margin_v=margin_v, 
            font_color=font_color, font_name=font_name
        )